﻿using FutianCloudAPIService.Utils;
using glTech.Log4netWrapper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace FutianCloudAPIService.Domains
{
    public class SystemDomain
    {
        static SystemDomain()
        {
            ReadCfg();
        }

        private static void ReadCfg()
        {
            try
            {
                var rootPath = PathUtil.GetRootPath();
                var xelement = XElement.Load(rootPath);

                var element = xelement.Element("WinStone");
                if (element != null)
                {
                    var ele = element.Element("WinStoneUrl");
                    if (ele != null)
                        WinStoneUrl = ele.Value;

                    ele = element.Element("OrcKey");
                    if (ele != null)
                        OrcKey = ele.Value;

                    ele = element.Element("OrcSecret");
                    if (ele != null)
                        OrcSecret = ele.Value;
                }

                element = xelement.Element("Nancy");
                if (element != null)
                {
                    var ele = element.Element("Port");
                    if (ele != null)
                        NancyPort = int.Parse( ele.Value);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError("read root.config error " + ex);
            }
        }

        internal async Task<string> Tail(int size = 10240)
        {
            var path = PathUtil.GetLogPath();

            var lastFile = Directory.GetFiles(path).OrderByDescending(o=>o).FirstOrDefault();

            using (FileStream fs = File.Open(lastFile,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
            {
                if(fs.Length < size)
                {
                    size = (int)fs.Length;
                }
                // Seek 1024 bytes from the end of the file
                fs.Seek(-size, SeekOrigin.End);

                // read 1024 bytes
                byte[] bytes = new byte[size];
                fs.Read(bytes, 0, size);

                string s = Encoding.Default.GetString(bytes);
                // or string s = Encoding.UTF8.GetString(bytes);
                // and output to console
                Console.WriteLine(s);

                return  "<div>" +s.Replace("\r\n","<br/>" ) + "</div>";
            }
        }

        public static string OrcSecret { get; private set; }
        public static string OrcKey { get; private set; }
        public static string WinStoneUrl { get; private set; }
        public static int NancyPort { get; private set; }
    }
}
